package 线程同步.不安全的案例;

import java.security.interfaces.ECKey;

public class BuyATicket {
    public static void main(String[] args) {
       buyTicket buyTicket= new buyTicket();
       new Thread(buyTicket,"小虎").start();
       new Thread(buyTicket,"小红").start();
       new Thread(buyTicket,"小米").start();
    }
}

class buyTicket implements Runnable{
    private static int ticket = 10;//票数
    private static Boolean test = true;//线程标记停止位
    @Override
    public void run() {
        while (true){
            if (test){
                try {
                    buy();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else {
                System.out.println("票卖完了");
                break;
            }
        }

    }
    //买票方法
    private void buy() throws InterruptedException {
        if (ticket<=0){
            test=false;
            return;
        }else {
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName()+"-->买了第"+ticket--+"张票");
        }
    }

}
